#!/bin/bash

# filename: compile_ffmpeg.sh

set -e

API=29
OS=android
PREFIX="${pwd}/out/"
ARCH=arm64
CPU=armv8-a
CFLAGS="-Os"
# i686-linux-android31-clang*

ANDROID_HOME=$HOME/.local/android
NDK=$ANDROID_HOME/ndk/23.1.7779620/
TOOLCHAINS=$NDK/toolchains/llvm/prebuilt/linux-x86_64
SYSROOT=$TOOLCHAINS/sysroot
NM=$TOOLCHAINS/bin/llvm-nm
STRIP=$TOOLCHAINS/bin/llvm-strip
PKG_CFG=$TOOLCHAINS/bin/llvm-config

function build_ffmpeg
{
# armv7a-linux-androideabi29-
CC=$TOOLCHAINS/bin/armv7a-linux-androideabi$API-clang
CXX=$TOOLCHAINS/bin/armv7a-linux-androideabi$API-clang++
CROSS_PREFIX=$TOOLCHAINS/bin/arm-linux-androideabi-   
echo "Start build ffmpeg...for $CPU"
SECONDS=0
./configure \
    --prefix=$PREFIX    \
    --disable-static    \
    --enable-shared     \
    --arch=$ARCH        \
    --cpu=$CPU          \
    --target-os=$OS     \
    --cc=$CC            \
    --cxx=$CXX          \
    --enable-cross-compile  \
    --cross-prefix=$CROSS_PREFIX    \
    --sysroot=$SYSROOT      \
    --nm=$NM                \
    --strip=$STRIP          \
    --pkg-config=$PKG_CFG   \
    --enable-jni            \
    --enable-mediacodec     \
    --enable-pic            \
    --enable-hwaccels       \
    --disable-doc           \
    --extra-cflags=$CFLAGS  \
    --extra-cxxflags=$CXXFLAGS  \
    --disable-x86asm

make -j4
make install
duration=$SECONDS
echo "Compile for $CPU success! cost time $(($duration / 60)) mins $(($duration % 60)) seconds"
}


# 编译 aarch64 位架构
# armv7a-linux-androideabi29-clang
# armv7a-linux-android29-clang
rm -rf ffmpeg-5.0
tar -xvf ffmpeg-5.0.tar.xz

ARCH=arm
CPU=armv7-a
PREFIX=$(pwd)/out/$OS/$CPU
cd ffmpeg-5.0
build_ffmpeg


# 编译 Arm 32 位架构
#ARCH=arm
#CPU=armv7-a
#PREFIX=$(pwd)/out/$OS/$CPU
#build_ffmpeg



echo "/mnt/nas/ssd/sh/out/android/x86_64/lib" > /etc/ld.so.conf.d/ffmpeg.conf
#可执行ffmpeg路径配置
cat > /etc/profile.d/myffmpeg.sh << EOF
#!/bin/bash
export inst=/mnt/nas/ssd/sh/out/android/x86_64
export PATH=\$inst/bin:\$PATH
EOF

#刷新配置文件
# 
ldconfig
source /etc/profile
ffmpeg -version







echo "/var/opt/myffmpeg/lib" > /etc/ld.so.conf.d/ffmpeg.conf
#可执行ffmpeg路径配置
cat > /etc/profile.d/myffmpeg.sh << EOF
#!/bin/bash
export inst=/var/opt/myffmpeg
export PATH=\$inst/bin:\$PATH
EOF

#刷新配置文件
# 
ldconfig
source /etc/profile
ffmpeg -version
























